<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>签到</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 70px 470px 50px;
            width: 100%;
            margin: 0 auto;
        }

        /**
        中部头部布局
         */
        .central-head {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 10px;
            padding: 5px;
        }

        /**
        表项限宽
         */
        .table td {
            max-width: 10vw;
        }

    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <button class="btn btn-secondary iconfont go-back-button"
                    onclick="window.location.href='card-issuance.html';">
                &#xe623;
            </button>
        </div>
        <!--    标题-->
        <div class="page-title" id="page-title">
            <script>
                document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                +"--签到"
            </script>
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">
        <div class="central-head">
            <!--                搜索框组件-->
            <div style="width: 900px;margin: auto">
                <div class="input-group">
                    <input id="search-input" type="text" class="form-control" placeholder="可按选手姓名/身份证号、指卡号、选手号码、组别、参赛项目、参赛单位、队伍名称、签到状态进行搜索 . . .">
                    <button class="btn btn-outline-secondary iconfont" type="button" onclick="showSearch()">&#xe60a;
                    </button>
                </div>
            </div>
            <button class="btn btn-primary" onclick="updateBatch('sign-in-table')" id="batchSign" >
                批量签到
            </button>
            <button class="btn btn-primary" onclick="downloadSignIn()">
                导出签到表
            </button>
        </div>
        <div class="table-responsive">
            <table id="sign-in-table" class="table table-sm table-bordered text-center">
                <thead>
                <tr>
                    <th>
                        <label>
                            全选
                            <input type="checkbox" onclick="selectMul('sign-in-table')">
                        </label>
                    </th>
                    <th>选手号码</th>
                    <th>指卡号</th>
                    <th>姓名</th>
                    <th>项目</th>
                    <th>组别</th>
                    <th>性别</th>
                    <th>身份证号</th>
                    <th>选手电话</th>
                    <th>参赛单位</th>
                    <th>接力队伍</th>
                    <th>替补</th>
                    <th>原指卡号</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="sign-in-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div>
            <!--    分页组件-->
            <ul class="pagination page-ul-flex" id="pagination">
            </ul>
        </div>
    </div>
    <!--尾部-->
    <div class="footer-grid">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--   下一步-->
        <div>
            <button class="btn btn-primary iconfont next-button" onclick="nextProgress(BATCH_PROGRESS,'batch.html')" id="btn-progress" disabled="true">
                &#xe65b;
            </button>
        </div>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script src="../js/request.js"></script>
<script>
    updateProgress("progress-bar", SIGN_IN_PROGRESS);

    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 9;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //更新id
    let updateId;
    //搜索内容
    let searchAll;

    /**
     * 下载签到表
     * @returns {Promise<void>}
     */
    async function downloadSignIn(){
        let url1 = new URL(SIGNIN_URL + "/download");
        url1.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url1).then(resp => {
            return resp.blob();
        }).then(blob => {
            // 创建一个指向 Blob 的 URL
            const url = window.URL.createObjectURL(blob);

            // 创建 <a> 元素
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '签到表.xlsx'; // 设置下载的文件名

            // 添加 <a> 到文档中，并触发点击事件
            document.body.appendChild(a);
            a.click();

            // 清理资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        });
    }

    /**
     * 批量签到
     */
    async function updateBatch(tableId) {
        let updateIds = [];
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            if (tr.firstElementChild.firstElementChild.checked) {
                updateIds.push(Number(tr.dataset.signInId));
            }
        }
        if (updateIds.length !== 0) {
            await fetch(SIGNIN_URL + "/updateBatch", {
                method: "POST",
                headers: new Headers({"Content-Type": "application/json"}),
                body: JSON.stringify(updateIds)
            });
            await showPage();
        }
    }

    /**
     * 单个签到
     */
    async function updateOne(status) {
        let url = new URL(SIGNIN_URL + "/updateOne");
        let bodyObject={};
        bodyObject.id=updateId;
        bodyObject.status=status;
        await fetch(url, {
            method: "POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(bodyObject)
        });
        await showPage();
    }


    /**
     * 点击搜索
     */
    async function showSearch() {
        pageNum = 1;
        await showPage();
    }

    /**
     * 多选框实现
     */
    function selectMul(tableId) {
        let mulSelect = document.querySelector("#" + tableId + " thead input");
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            tr.firstElementChild.firstElementChild.checked = mulSelect.checked;
        }
    }

    /**
     * 表格渲染
     */
    async function drawSignInTable(records) {
        let mulSelect = document.querySelector("#sign-in-table thead input");
        mulSelect.checked = false;
        let tableBody = document.getElementById("sign-in-tbody");
        tableBody.innerHTML = "";

        let url=new URL(PROJECT_URL + "/getEarliestProject");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        let res = await fetch_http({
            url:url,
            method:'GET'
        })
        


        for (let record of records) {
            let trElement = document.createElement("tr");
            trElement.dataset.signInId = record.id;
            let tdElement0 = document.createElement("td");
            let inputElement = document.createElement("input");
            inputElement.type = "checkbox";
            tdElement0.append(inputElement);
            let tdElement1 = document.createElement("td");
            tdElement1.textContent = record.athleteNumber;
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.newCard;
            let tdElement3 = document.createElement("td");
            tdElement3.textContent = record.athleteName;
            let tdElement4 = document.createElement("td");
            let content = "";
            for (let projectName of record.projectNames) {
                content += projectName + ","
            }
            tdElement4.textContent = content.slice(0, -1);
            let tdElement5 = document.createElement("td");
            tdElement5.textContent = record.groupName;
            let tdElement6 = document.createElement("td");
            tdElement6.textContent = record.gender;
            let tdElement7 = document.createElement("td");
            tdElement7.textContent = record.idNumber;
            let tdElement8 = document.createElement("td");
            tdElement8.textContent = record.athletePhone;
            let tdElement9 = document.createElement("td");
            tdElement9.textContent = record.unitName;
            let tdElement10 = document.createElement("td");
            tdElement10.textContent = record.teamName;
            let tdElement11 = document.createElement("td");
            tdElement11.textContent = record.substitute;
            let tdElement12 = document.createElement("td");
            tdElement12.textContent = record.oldCard;
            let tdElement13 = document.createElement("td");
            let buttonElement2 = document.createElement("button");

            if (record.signInStatus === "否") {
                buttonElement2.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                buttonElement2.textContent = "未签到";

            } else {
                buttonElement2.classList.add("btn", "btn-success", "btn-sm", "iconfont");
                buttonElement2.textContent = "已签到";
                document.getElementById("btn-progress").disabled=false;
            }

            if(res.code == 200 && new Date().getTime() > new Date(res.data.startTime).getTime()){
                document.getElementById("batchSign").disabled = true;
                buttonElement2.disabled=true
            }else{
                buttonElement2.addEventListener("click", async () => {
                    updateId = record.id;
                    if (buttonElement2.textContent === "未签到") {
                        await updateOne("是")
                    } else {
                        await updateOne("否");
                    }
                });
                buttonElement2.disabled=false
                document.getElementById("batchSign").disabled = false;
            }
            
            tdElement13.append(buttonElement2);
            trElement.append(tdElement0, tdElement1, tdElement2, tdElement3, tdElement4,
                tdElement5, tdElement6, tdElement7, tdElement8,
                tdElement9, tdElement10, tdElement11, tdElement12, tdElement13);
            tableBody.append(trElement);
        }
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let searchInput = document.getElementById("search-input");
        searchAll = searchInput.value;
        let url = new URL(SIGNIN_URL + "/searchAll");
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        url.searchParams.set("searchAll", searchAll);
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            drawSignInTable(records);
        }).catch(error => {
            console.log("分页错误：", error);
        });

    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize = Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);

        
        let url=new URL(PROJECT_URL + "/getEarliestProject");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        let res = await fetch_http({
            url:url,
            method:'GET'
        })
        if(res.code == 200 && new Date().getTime() > new Date(res.data.startTime).getTime()){
            let batchSign=document.getElementById("batchSign")
            batchSign.disabled = true;
        }
    }

    if (window.sessionStorage.getItem("competitionId")) {
        (async () => {
            await showPage();
        })();
    }

</script>
</body>
</html>